# -*- coding:utf-8 -*-

import MySQLdb
from collections import defaultdict


class MySQL_API(object):

    def __init__(self, **con_info):
        mysql_info = defaultdict()
        mysql_info['host'] = con_info.get('host', '127.0.0.1')
        mysql_info['port'] = con_info.get('port', 3306)
        mysql_info['charset'] = con_info.get('charset', 'utf8')
        mysql_info['user'] = con_info['username']
        mysql_info['db'] = con_info['db_name']
        if 'passwd' in con_info:
            mysql_info['passwd'] = con_info['passwd']

        self.conn = MySQLdb.connect(**mysql_info)

        self.cursor = self.conn.cursor()
        #self.cursor.execute("truncate table jdinfo")
        #self.conn.commit()

    def process_item(self, items):

        insert_cmd = "insert into jdinfo (productId, productName, productColor, orderTime, commentTime, score, " \
                     "userClientShow, userLevelName, commentContent, commentplusafterDays, commentplusContent) " \
                     "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

        data = (items["productId"], items["productName"], items["productColor"], items["orderTime"],
                items["commentTime"], items["score"], items["userClientShow"], items["userLevelName"],
                items["commentContent"], items["commentplusafterDays"], items["commentplusContent"])

        try:
            self.cursor.execute(insert_cmd, data)
            self.conn.commit()
        except Exception, e:
            print(Exception, e)
            self.conn.rollback()
        self.conn.close()


if __name__ == "__main__":
    con_sql_info = {'username': 'root', 'passwd': 'root', 'db_name': 'test'}
    SQL = MySQL_API(**con_sql_info)
    SQL.cursor.execute('desc jdinfo;')
    rows = SQL.cursor.fetchall()
    print rows
